package com.xywh.micro_warehousing.mvp.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.xw.repo.XEditText;
import com.xywh.micro_warehousing.R;
import com.xywh.micro_warehousing.di.component.DaggerLoginComponent;
import com.xywh.micro_warehousing.di.module.LoginModule;
import com.xywh.micro_warehousing.mvp.contract.LoginContract;
import com.xywh.micro_warehousing.mvp.presenter.LoginPresenter;
import com.xywh.micro_warehousing.mvp.ui.entity.Login;

import org.jetbrains.annotations.NotNull;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.jessyan.armscomponent.commonres.utils.CProgressDialogUtils;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import me.jessyan.armscomponent.commonsdk.utils.Utils;
import me.jessyan.retrofiturlmanager.RetrofitUrlManager;
import pub.devrel.easypermissions.EasyPermissions;

import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.ACTIVITY_LOGIN)
public class LoginActivity extends BaseActivity<LoginPresenter> implements LoginContract.View, EasyPermissions.PermissionCallbacks {

    @BindView(R.id.btnRight)
    ImageView mBtnRight;
    @BindView(R.id.xet_account)
    XEditText xetAccount;
    @BindView(R.id.xet_pwd)
    XEditText xetPwd;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.tv_forget_password)
    TextView tvForgetPassword;
    @BindView(R.id.tv_register)
    TextView tvRegister;
    private View.OnClickListener mRightListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {


        }
    };
    private String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);

        if (requestCode == 104) {

        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        ArmsUtils.makeText(this, "相关权限获取成功");
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        ArmsUtils.makeText(this, "请同意相关权限，否则功能无法使用");
    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerLoginComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .loginModule(new LoginModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_login; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        ToolbarUtils.initToolbarTitleNoBack(this, getString(R.string.activity_login));
        initRightBtn();
        if (!TextUtils.isEmpty(mSharedPreferencesHelper.getString(BaseConstants.USERNAME)) && !TextUtils.isEmpty(mSharedPreferencesHelper.getString(BaseConstants.PASSWORD))) {
            xetAccount.setText(mSharedPreferencesHelper.getString(BaseConstants.USERNAME));
            xetPwd.setText(mSharedPreferencesHelper.getString(BaseConstants.PASSWORD));
        }

        if (!TextUtils.isEmpty(mSharedPreferencesHelper.getString(BaseConstants.IP)) && !TextUtils.isEmpty(mSharedPreferencesHelper.getString(BaseConstants.PORT))) {
            RetrofitUrlManager.getInstance().setGlobalDomain(getUrl());
        }
    }

    private void initRightBtn() {
//        mBtnRight.setImageDrawable(getResources().getDrawable(R.drawable.icon_setting));
        mBtnRight.setImageDrawable(getResources().getDrawable(R.drawable.icon_setting));
        mBtnRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toSettingPage();
            }
        });
    }

    private void toSettingPage() {
        Utils.navigation(LoginActivity.this, RouterHub.ACTIVITY_SETTING);
    }

    @Override
    public void getLoginDataSuccess(Login entityData) {

        if (entityData.getCode() == 200) {
            showMessage("登录成功");

//        mSharedPreferencesHelper.putString(BaseConstants.TOKEN, login.getData().getAccess_token());
            mSharedPreferencesHelper.putString(BaseConstants.UID, String.valueOf(entityData.getData().getID()));
            mSharedPreferencesHelper.putString(BaseConstants.USERNAME, getAccount());
            mSharedPreferencesHelper.putString(BaseConstants.NICK_NAME, entityData.getData().getName());
            mSharedPreferencesHelper.putString(BaseConstants.PASSWORD, getPwd());
            mSharedPreferencesHelper.putString(BaseConstants.MOBILE_PHONE, entityData.getData().getMobilePhone());
//        mSharedPreferencesHelper.putString(BaseConstants.API_USER_NAME, login.getApiUserName());
//        mSharedPreferencesHelper.putString(BaseConstants.API_PWD, login.getApiPwd());
            Utils.navigation(this, RouterHub.ACTIVITY_MAIN);
            killMyself();
        } else {
            if (!TextUtils.isEmpty(entityData.getMessage()))
                showMessage(entityData.getMessage());
        }
    }

    @NotNull
    private String getAccount() {
        return xetAccount.getText().toString().trim();
    }

    @NotNull
    private String getPwd() {
        return xetPwd.getText().toString().trim();
    }

    @Override
    public void showLoading() {
        CProgressDialogUtils.showProgressDialog(this);
    }

    @Override
    public void hideLoading() {
        CProgressDialogUtils.cancelProgressDialog();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @OnClick({R.id.tv_forget_password, R.id.tv_register, R.id.btn_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_forget_password:
                Utils.navigation(this, RouterHub.ACTIVITY_FORGET_PASSWORD);
                break;
            case R.id.tv_register:
                Utils.navigation(this, RouterHub.ACTIVITY_REGISTER);
                break;
            case R.id.btn_login:

                if (TextUtils.isEmpty(mSharedPreferencesHelper.getString(BaseConstants.IP)) || TextUtils.isEmpty(mSharedPreferencesHelper.getString(BaseConstants.PORT))) {
                    showMessage("请先设置IP和Port");
                    toSettingPage();
                    return;
                }

                if (TextUtils.isEmpty(getAccount())) {
                    showMessage("请输入登录帐号");
                    return;
                }
                if (TextUtils.isEmpty(getPwd())) {
                    showMessage("请输入登录密码");
                    return;
                }
                if (getPermission()) {

//                    if (Build.VERSION.SDK_INT >= 23) {
//                        if (!Settings.canDrawOverlays(this)) {
//                            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
//                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                            startActivityForResult(intent, 1);
//                        } else {
//                        }
//                    }
                    getLoginData();

//            Utils.navigation(this, RouterHub.ACTIVITY_MAIN);
                }
                break;
        }
    }

    private boolean getPermission() {
        if (EasyPermissions.hasPermissions(this, permissions)) {
            return true;
        } else {
//            EasyPermissions.requestPermissions(this, "需要获取您的相册、照相使用权限", 1, permissions);
            EasyPermissions.requestPermissions(this, "需要获取您的使用权限", 1, permissions);
            return false;
        }

    }

    private void getLoginData() {
        HashMap<String, String> map = new HashMap<>();
        map.put("loginName", getAccount());
        map.put("password", getPwd());
        mPresenter.getLoginData(map);
    }
}
